//
//  NetworkSettingsVC.swift
//  MIFI
//
//  Created by 金嗓子卡卡 on 2019/4/21.
//  Copyright © 2019 NJMifi. All rights reserved.
//

import UIKit

class NetworkSettingsVC: RootVC {
    
    private lazy var autoSwitch: UISwitch = {
        let sw = UISwitch(frame: CGRect(x: 0, y: 10, width: 50, height: 30))
        sw.right = screenWidth - 8
        sw.addTarget(self, action: #selector(switchChangeValue(sender:)), for: .valueChanged)
        sw.tag = 0
        return sw
    }()
    
    private lazy var roamingSwitch: UISwitch = {
        let sw = UISwitch(frame: autoSwitch.frame)
        sw.addTarget(self, action: #selector(switchChangeValue(sender:)), for: .valueChanged)
        sw.tag = 1
        return sw
    }()
    
    private var names = ["Set Network Mode",
                         "Automatic Connection",
                         "Roaming"]
    
    private var modes = ["Auto","4G","3G","2G"]
    private var modeName = "" {
        didSet {
            tableView.reloadData()
        }
    }
    
    private lazy var tableView: UITableView = {
        let tab = UITableView(frame: CGRect(x: 0, y: naviView!.bottom, width: screenWidth, height: screenHeight - naviView!.bottom), style: .grouped)
        tab.backgroundColor = whiteColor
        tab.rowHeight = 50
        tab.delegate = self
        tab.dataSource = self
        tab.separatorStyle = .none
        tab.isScrollEnabled = false
        return tab
    }()
    
    override func configView() {
        configNaviView(title: "Network Settings")
        view.addSubview(tableView)
        net_getDeviceInfoList {[weak self] (model) in
            if model != nil {
                var isAuto = false
                if model?.dialMode!.caseInsensitiveCompare("auto_dial") == .orderedSame {
                    isAuto = true
                }
                UserInfoManager.shared().isAutoConnected = isAuto
                self?.autoSwitch.isOn = isAuto
                var isRoaming = false
                if !(model?.roamSettingOption!.caseInsensitiveCompare("off") == .orderedSame) {
                    isRoaming = true
                }
                self?.roamingSwitch.isOn = isRoaming
            }
        }
        net_getNetMode {[weak self] (modeStr) in
            self?.modeName = modeStr
        }
    }
    
    @objc private func switchChangeValue(sender:UISwitch) {
        var network : NetworkManager
        let connectMode = autoSwitch.isOn ? "auto_dial" : "manual_dial"
        let roamMode = roamingSwitch.isOn ? "on" : "off"
//        if sender.tag == 0 {
            network = .setNetConnectModel(connectMode: connectMode, roamMode: roamMode)
//        }else {
//            network = .setNetRoamModel(connectMode: connectMode, roamMode: roamMode)
//        }
        net_setNet(request: network) {[weak self] (value) in
            if !value {
                sender.isOn = !sender.isOn
            }else {
//                self?.navigationController?.popViewController(animated: true)
            }
        }
    }
    
    private func setNetMode(index:Int) {
        net_setNetMode(mode: index) {[weak self] (success) in
            if success {
                self?.modeName = self!.modes[index]
                
                 net_connect()
                
            }
        }
    }
    
}

extension NetworkSettingsVC : UITableViewDelegate, UITableViewDataSource{
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return names.count
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = UITableViewCell(style: .default, reuseIdentifier: "cell")
        
        cell.textLabel?.text = names[indexPath.row]
        cell.textLabel?.font = UIFont.systemFont(ofSize: 18)
        cell.textLabel?.textColor = textGray
        cell.selectionStyle = .none
        if indexPath.row == 0 {
            _ = cell.contentView.subviews.map{$0.removeFromSuperview()}
            let label = UILabel(frame: CGRect(x: 0, y: 0, width: 50, height: 50))
            label.right = screenWidth - 50
            label.text = modeName
            label.font = cell.textLabel?.font
            label.textColor = cell.textLabel?.textColor
            label.backgroundColor = clearColor
            label.textAlignment = .right
            cell.contentView.addSubview(label)
            cell.accessoryType = .disclosureIndicator
        }else if indexPath.row == 1 {
            cell.contentView.addSubview(autoSwitch)
        }else if indexPath.row == 2 {
            cell.contentView.addSubview(roamingSwitch)
        }
        let line = UIView(frame: CGRect(x: 8, y: 50 - 0.5, width: screenWidth - 16, height: 0.5))
        line.backgroundColor = textGray
        cell.contentView.addSubview(line)
        
        return cell
    }
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        guard indexPath.row == 0 else {
            return
        }
        let alertView = PickerAlertView(title: "Network", data: modes)
        alertView.handle = ({[weak self] index in
            self?.setNetMode(index: index)
        })
        let alertVC = CustomAlertVC(contentType: .animation(alertView))
        alertVC.show()
    }
    
    func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
        return 0
    }
    
    func tableView(_ tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat {
        return 0
    }
    
    func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
        return nil
    }
    
    func tableView(_ tableView: UITableView, viewForFooterInSection section: Int) -> UIView? {
        return nil
    }
}
